//
//  CSOAuthViewController.swift
//  weibo
//
//  Created by 崔顺建 on 16/8/9.
//  Copyright © 2016年 cui. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
//appSecret
let appSecret = "ccad0810adc335b668e0e2ced259644d"
//appKey
let webAppKey = "3962712806"
//授权页http://www.itcast.cn
let redirect_Uri = "http://www.itcast.cn"
class CSOAuthViewController: UIViewController {
    //MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        webView.opaque = false
        
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        resquestLoginNet()
        setNavUp()
    }
    private func setNavUp() {
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancleButton")
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillButton")
    navigationItem.title = "微博登录"
    }
    //取消
    @objc private func cancleButton() {
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFillButton() {
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15201455605';document.getElementById('passwd').value = '1594040902csj'")
     
    }
     private func resquestLoginNet() {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(webAppKey)&redirect_uri=\(redirect_Uri)"
        
        print(url)
        
        //准备发送网络请求(urlrequest)
        let resquest = NSURLRequest(URL: NSURL(string: url)!)
        //通过webview加载页面
        webView.loadRequest(resquest)
    
    }
    

}
//MARK: -UIWebViewDelegate设置代理
extension CSOAuthViewController :UIWebViewDelegate{
    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print("========\(request.URL?.absoluteString)")//拿到完整的URL字符串
        guard let url = request.URL else {
            return false
        }
        if !url.absoluteString.hasPrefix(redirect_Uri) {
        
            return true
        
        }
        
        if let query1 = url.query where query1.hasPrefix("code=") {
        //获取code
           // print(query1)
            //截取字符串
            let code = query1.substringFromIndex("code=".endIndex)
        print(code)
            CSJUserAccountViewModel.shardUserAccount.getAccessToken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                
                print("==========成功")
                NSNotificationCenter.defaultCenter().postNotificationName(switchRootVController, object: self)
                    
                    
                }else {
                
                print("=============失败")
                }
            })
            
        }else {
        
        dismissViewControllerAnimated(true, completion: nil)
            
        }
        
        return false
    }
    
//开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}















